/*
 * @(#)org.example 2020/3/25/0025
 *
 * Copy Right@ 人人译视界
 */


package org.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/3/25/0025
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class NIOFileChannelDemo {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("d:\\workspaces\\nio-demo\\1.txt");
		FileChannel fcRead = fis.getChannel();

		FileOutputStream fos = new FileOutputStream("d:\\workspaces\\nio-demo\\2.txt");
		FileChannel fcOut = fos.getChannel();

		ByteBuffer buffer = ByteBuffer.allocate(512);
		while(true) {
			// 必须要先clear，否则会出现后续循环时position和limit相等导致read的返回值为0，死循环
			buffer.clear();
			int length = fcRead.read(buffer);
			if (length == -1) {
				break;
			}
			buffer.flip();
			fcOut.write(buffer);
		}
		fcRead.close();

		RandomAccessFile file = new RandomAccessFile(new File("1.txt"), "rw");
		FileChannel fc = file.getChannel();
		MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 5);
		mbb.put(0, (byte) 'Y');// 第一位修改
		mbb.put(4, (byte) 'q');// 第位位修改
		mbb.put(5, (byte) 'e');// 报索引越界异常
		file.close();
	}
}
